<template>
  <!-- 配种列表 -->
  <div>
    配种日期:
     <el-date-picker
        v-model="form.startDate"
        type="date"
        placeholder="请选择"
        style="width: 150px;"
      />~
      <el-date-picker
        v-model="form.endDate"
        type="date"
        placeholder="请选择"
        style="width: 150px;"
      />
    &emsp;&emsp; 种母耳号：
    <el-input style="width: 150px;" v-model = form.motherEarNumber > </el-input>
    &emsp; &emsp; &emsp; 
      负责人：  <el-select v-model="form.chargePerson" placeholder="负责人" clearable style="width: 150px;"  >
        <el-option v-for="item in procationDtas" :label="item.firstName" :value="item.employeeId"  />
      </el-select>&emsp; &emsp;

    <el-button :icon="Search" type="danger" @click="getDatas()" >查询</el-button
    >
    <el-button type="danger" @click="resultForm()" >重置</el-button><br /><br />
    <el-button type="danger" @click="router.push('/Mother_HybirdizationAdd')" :icon="Plus">新增</el-button>
    <el-button type="danger" @click="allDeleteCottage()" :icon="Delete">删除</el-button>
    <el-button type="danger" :icon="Plus">审核</el-button>
  </div>
  <el-table
    :header-cell-style="{
      height: '100px',
      fontSize: '13px',
      color: 'black',
      backgroundColor: 'antiquewhite'
    }"
    :data="tableData"
    border
    style="width: 100%"
    @selection-change="handleSelectionChange"
  >
   <el-table-column type="selection"  width="55" />
    <el-table-column label="序号">
      <template #default="{ $index }">
        {{ $index + 1 }}
      </template>
    </el-table-column>
    <el-table-column prop="createTime" label="配种日期" width="180">
      <template v-slot="scope">
        {{ scope.row.createTime.substring(0, 19).replace('T', ' ') }}
      </template>
    </el-table-column>
   
    <el-table-column prop="motherEarNumber" label="耳号" width="130" />
    <el-table-column prop="motherTypeName" label="种母品种" width="130" />
    <el-table-column prop="fatherEarNumber" label="首配公羊" width="130" />
    <el-table-column prop="fatherTypeName" label="种公品种" width="130" />
    <el-table-column prop="hybridizationTypeName" label="配种方式" width="130" />
    <el-table-column prop="estrusTypeName" label="种母发情类型" width="130" />
    <el-table-column prop="mark" label="首配评分" width="80" >
      <template v-slot="scope" >
        {{ scope.row.mark }}分
      </template>
    </el-table-column>
    <el-table-column prop="nowCottageName" label="当前栋舍" width="130" />
    <el-table-column prop="nowFiedName" label="当前栏位" width="120" />
    <el-table-column prop="toCottageName" label="转入栋舍" width="120" />
    <el-table-column prop="toFieIdName" label="转入栏位" width="130" />
    <el-table-column prop="breedStatuId" label="繁殖状态" width="120">
      <template v-slot="scope" >
          <v-tag v-if="scope.row.breedStatuId==1">后备空怀</v-tag>
            <v-tag v-else="scope.row.breedStatuId==2">返青空怀</v-tag>
            <v-tag v-else="scope.row.breedStatuId==3">未孕空怀</v-tag>
            <v-tag v-else="scope.row.breedStatuId==4">流产空怀</v-tag>
            <v-tag v-else="scope.row.breedStatuId==5">空胎空怀</v-tag>
            <v-tag v-else="scope.row.breedStatuId==6">妊娠</v-tag>
            <v-tag v-else="scope.row.breedStatuId==7">哺乳</v-tag>
      </template>
    </el-table-column>
   <el-table-column prop="createTime" label="事件日期" width="180">
      <template v-slot="scope">
        {{ scope.row.createTime.substring(0, 19).replace('T', ' ') }}
      </template>
    </el-table-column>
    <el-table-column prop="chargePersonName" label="负责人" />
    <el-table-column prop="createName" label="创建人" />
    <el-table-column prop="createTime" label="创建时间" width="180">
      <template v-slot="scope">
        {{ scope.row.createTime.substring(0, 19).replace('T', ' ') }}
      </template>
    </el-table-column>
    <el-table-column prop="updateName" label="修改人" />
    <el-table-column prop="updateTime" label="修改时间" width="180">
      <template v-slot="scope">
        {{
          scope.row.updateTime == null
            ? ''
            : scope.row.updateTime.substring(0, 19).replace('T', ' ')
        }}
      </template>
    </el-table-column>
    <el-table-column prop="examName" label="审核人" />
    <el-table-column prop="examTime" label="审核时间" width="180">
      <template v-slot="scope">
        {{
          scope.row.examTime == null
            ? ''
            : scope.row.examTime.substring(0, 19).replace('T', ' ')
        }}
      </template>
    </el-table-column> 
    <el-table-column prop="documentNumber" label="单据号" width="180" />
    <el-table-column label="操作" width="120">
      <template v-slot="scope">
        <el-link @click="detailMotherHybridization(scope.row.motherHybridizationId)" type="primary">编辑</el-link>&emsp;
        <el-link @click="deleteCottage(scope.row.motherHybridizationId)" type="primary">删除</el-link>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
    v-model:current-page="form.pageIndex"
    v-model:page-size="form.pageSize"
    :page-sizes="[5, 10, 15, 20]"
    :background="true"
    layout="total, sizes, prev, pager, next, jumper"
    :total="form.totalCount"
    @size-change="handleSizeChange1"
    @current-change="handleCurrentChange1"
  />
    <!-- 对话框修改 -->
  <el-dialog v-model="dialogFormVisible" title="修改配种信息" width="600" >
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
    
      :model="ruleFormf"
      :rules="rules"
      label-width="auto"
      status-icon
       class="myDialogClass"
    >
    <el-form-item el-form-item label="种母耳号:" prop="fatherSleepInforId">
       <el-select v-model="ruleFormf.motherSleepInforId" placeholder="请选择" style="width: 150px;" clearable >
        <el-option v-for="item in motherDatas" :label="item.earNumber" :value="item.sleepInforId"   />
      </el-select>
      </el-form-item>
      <el-form-item el-form-item label="配种公羊:" prop="fatherSleepInforId">
       <el-select v-model="ruleFormf.fatherSleepInforId" placeholder="请选择" style="width: 150px;" clearable >
        <el-option v-for="item in surnameDatas" :label="item.earNumber" :value="item.sleepInforId"   />
      </el-select>
      </el-form-item>
      <el-form-item label="配种方式:" prop="hybridizationTypeId">
       <el-select style="width: 150px;" v-model="ruleFormf.hybridizationTypeId" placeholder="请选择"  clearable  >
        <el-option v-for="item in hybridizationTypeDatas" :label="item.hybridizationTypeName" :value="item.hybridizationTypeId" />
      </el-select>
      </el-form-item>
      <el-form-item label="种母发情类型:" prop="estrusTypeId">
        <el-select style="width: 150px;" v-model="ruleFormf.estrusTypeId" placeholder="请选择"  clearable  >
        <el-option v-for="item in estrusDatas" :label="item.estrusTypeName" :value="item.estrusTypeId" />
      </el-select>
      </el-form-item>

      <el-form-item label="转入位置（栋舍）:"prop="toCottageId"  >
         <el-select style="width: 150px;"  v-model="ruleFormf.toCottageId" placeholder="请选择"  @change="getField(Number(ruleFormf.toCottageId))"   clearable  >
        <el-option v-for="item in cottagesDatas" :label="item.cottageName" :value="item.cottagesId"/>
      </el-select>
    </el-form-item>

      <el-form-item label="转入位置(栏位):" prop="toFieIdId" >
          <el-select style="width: 150px;" v-model="ruleFormf.toFieIdId" placeholder="请选择" clearable  >
        <el-option v-for="item in Fields" :label="item.fieIdName" :value="item.fieIdId"  />
      </el-select>
      </el-form-item>
        
      <el-form-item label="负责人:" prop="chargePerson" >
           <el-select v-model="ruleFormf.chargePerson" placeholder="请选择" clearable style="width: 150px;" >
        <el-option v-for="item in procationDtas" :label="item.firstName" :value="item.employeeId"  />
      </el-select>
      </el-form-item>
      
        
        
    </el-form>
    <template #footer>
      <div class="dialog-footer">
         <el-button type="danger"  @click="resetForm(ruleFormRef)">清空</el-button>
        <el-button type="danger" @click="resetForm1(ruleFormRef)">返回</el-button>
        <el-button type="danger" @click="submitForm(ruleFormRef)">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup lang="ts">
import {
  Delete,
  Edit,
  Search,
  Plus,
  Setting,
  SuccessFilled
} from '@element-plus/icons-vue';
import { reactive, ref, onMounted } from 'vue';
import axios from 'axios';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus';
//调用持久化
import { useCounterStore } from '@/stores/counter';
const counterStore = useCounterStore();
const route = useRoute();
const router = useRouter();


//获取负责人信息
const procationDtas:any = ref([])
const getProcationDatas = () => {
  axios.post("http://localhost:5039/api/Cottages/SearchEmployees", {}).then(res => {
    procationDtas.value = res.data.data
  })
}


onMounted(() => {
  getProcationDatas();
  getDatas();
});
const form = reactive({
  pageIndex: 1,
  pageSize: 5,
  totalCount: 0,
  totalPage: 0,
  startDate: '',
  endDate:'',
  motherEarNumber: '',
  chargePerson:'',
});
//获取查询显示信息
const tableData = ref([]);
const getDatas = () => {

  const request: any = ref({})
  request.startDate = form.startDate
  request.endDate = form.endDate
  request.pageIndex = form.pageIndex
  request.pageSize = form.pageSize
  request.motherEarNumber = form.motherEarNumber
request.chargePerson = form.chargePerson||0
  axios
    .post('http://localhost:5039/api/ProductionManagement/MotherHybridizationSearch', request)
    .then((res) => {
      console.log(res.data);
      console.log(res.data.data)
      tableData.value = res.data.data;
      form.totalCount = res.data.totalCount;
      form.totalPage = res.data.totalPage;
    });
};

//分页相关
const handleSizeChange1 = (val: any) => {
  form.pageSize = val;
  getDatas();
};

const handleCurrentChange1 = (val: any) => {
  form.pageIndex = val;
  getDatas();
};

//重置
const resultForm = () => {
  form.chargePerson = ''
  form.startDate = ''
  form.endDate = ''
  form.motherEarNumber=''
}


//全选反选
const multipleSelection = ref([])
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val
}


//删除
//配种信息删除（批量）

const allDeleteCottage = () => {
  var request: any = ref({})
  let idsArry: any = [];
  if (multipleSelection.value.length < 1) {
    ElMessage.error("一项都没选");
    return;
  }
  multipleSelection.value.forEach((c:any) => {
    idsArry.push(c.motherHybridizationId)
  });
  
request.ids = idsArry.toString()
request.deleteId=counterStore.employeeId
console.log(request)
   ElMessageBox.confirm(
    '确认删除吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      axios.delete("http://localhost:5039/api/ProductionManagement/MotherHybridizationAllDelete",{
         data: request,
        headers: {
       'Content-Type': 'application/problem+json;charset=UTF-8'
     }
       } ).then(res => {
    if (res.data.code > 0) {
      ElMessage.success("删除成功");
      getDatas();
    } else {
      ElMessage.error("删除失败，再试试...");
      return;
    }
  })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })

  
}
//配种信息删除
const deleteCottage = (motherHybridizationId: number) => {
  var request: any = ref({})
  request.ids = motherHybridizationId.toString();
  request.deleteId=counterStore.employeeId
  ElMessageBox.confirm(
    '确认删除吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      axios.delete("http://localhost:5039/api/ProductionManagement/MotherHybridizationAllDelete",{
         data: request,
        headers: {
       'Content-Type': 'application/problem+json;charset=UTF-8'
     }
       } ).then(res => {
    if (res.data.code > 0) {
      ElMessage.success("删除成功");
      getDatas();
    } else {
      ElMessage.error("删除失败，再试试...");
      return;
    }
  })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })
}


//修改配种信息
const dialogFormVisible = ref(false)

const ruleFormf = reactive({
  motherHybridizationId: '',
  motherSleepInforId:'',
  fatherSleepInforId: '',
  hybridizationTypeId: '',
  estrusTypeId: '',
  mark: '',
  toCottageId: '',
  toFieIdId: '',
  documentNumber: '',
  chargePerson: '',
  updateId:counterStore.employeeId
})

//反添配种信息
const detailMotherHybridization = (motherHybridizationId: number) => {
  dialogFormVisible.value=true
  getProcationDatas1();
  getSurnameDatas();
  getMotherDatas();
  getHybridizationTypes();
  getEstrusDatas();
  getCottages();
  const request: any = ref({})
  request.motherHybridizationId=motherHybridizationId
  axios.post("http://localhost:5039/api/ProductionManagement/MotherHybridizationDetail", request).then(res => {
    console.log(res.data.item)
    ruleFormf.motherHybridizationId = res.data.item.motherHybridizationId
    ruleFormf.motherSleepInforId = res.data.item.motherSleepInforId
    ruleFormf.fatherSleepInforId = res.data.item.fatherSleepInforId
    ruleFormf.hybridizationTypeId = res.data.item.hybridizationTypeId
    ruleFormf.estrusTypeId = res.data.item.estrusTypeId
    ruleFormf.mark = res.data.item.mark
    ruleFormf.toCottageId = res.data.item.toCottageId
    getField(res.data.item.toCottageId);
    ruleFormf.toFieIdId = res.data.item.toFieIdId
    ruleFormf.documentNumber = res.data.item.documentNumber
    ruleFormf.chargePerson = res.data.item.chargePerson
  })
}

const ruleFormRef = ref<FormInstance>();
//非空验证
const rules = reactive<FormRules>({
  motherSleepInforId: [{ required: true, message: '种母未选择', trigger: 'change' }],
  fatherSleepInforId: [{ required: true, message: '配种公羊未选择', trigger: 'change' }],
  hybridizationTypeId: [{ required: true, message: '配种方式未选择', trigger: 'change' }],
  estrusTypeId: [{ required: true, message: '种母发情类型未选择', trigger: 'change' }],
  toCottageId: [{ required: true, message: '转入栋舍未选择', trigger: 'change' }],
  toFieIdId: [{ required: true, message: '转入栏位未选择', trigger: 'change' }],
  chargePerson: [{ required: true, message: '负责人未选择', trigger: 'change' }],
});



//获取负责人信息
const procationDtas1:any = ref([])
const getProcationDatas1 = () => {
  axios.post("http://localhost:5039/api/Cottages/SearchEmployees", {}).then(res => {
    procationDtas1.value = res.data.data
  })
}

//首配公羊耳号信息
const surnameDatas:any = ref([])
const getSurnameDatas = () => {
  axios.get("http://localhost:5039/api/SleepBegin/SelectEarMale").then(res => {
    surnameDatas.value=res.data.data
  })
}
//种母耳号信息
const motherDatas: any = ref([])
const getMotherDatas = () => {
  axios.get("http://localhost:5039/api/SleepBegin/SelectEarFeMale").then(res => {
    motherDatas.value=res.data.data
  })
}

//配种方式
const hybridizationTypeDatas: any = ref([])
const getHybridizationTypes = () => {
  axios.get("http://localhost:5039/api/ProductionManagement/SearchHybridizationTypes").then(res => {
    hybridizationTypeDatas.value=res.data.data
  })
}

//种母发情类型
const estrusDatas  :any= ref([])
const getEstrusDatas = () => { 
  axios.get("http://localhost:5039/api/ProductionManagement/SearchEstrusTypes").then(res => {
    estrusDatas.value = res.data.data
  })
}

//获取栋舍信息
const cottagesDatas:any=ref([])
const getCottages = () => {
  axios.post("http://localhost:5039/api/Cottages/CottageList", {}).then(res => {
    cottagesDatas.value=res.data.data
  })
}

//获取栋舍下栏位信息
const Fields: any = ref([])
const getField = (cottagesId: number) => {
  ruleFormf.toFieIdId=''
  const request: any = ref({})
  request.cottagesId = cottagesId;
  axios.post("http://localhost:5039/api/Cottages/SearchFields", request).then(res => {
    Fields.value=res.data.data
  })
}

//清空
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
//返回
const resetForm1 = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  dialogFormVisible.value = false
}

//修改方法
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log(ruleFormf)
      axios.put("http://localhost:5039/api/ProductionManagement/MotherHybridizationUpdate", ruleFormf).then(res => {
        if (res.data.code > 0) {
          ElMessage.success("信息修改成功")
          dialogFormVisible.value = false
      getDatas();
        } else {
          ElMessage.error("信息修改失败，再试试~~");
          return
        }
      })
      
    } else {
      console.log('error submit!', fields);
    }
  });
};

</script>

<style scoped></style>
